package me.minecraft.plugin.filemonitor;

import lombok.Getter;
import org.bukkit.Bukkit;

import java.io.File;
import java.util.Objects;

/**
 * @author langle__
 * @version 1.0
 */
@Getter
public class FileListener {

    private final File file;
    private final String command;
    private long lastModifiedTime;

    public FileListener(File file, String command) {
        this.file = file;
        this.command = command;
        this.lastModifiedTime = file.lastModified();
    }

    public boolean isFileModified() {
        long currentModifiedTime = file.lastModified();
        if (lastModifiedTime != currentModifiedTime) {
            this.lastModifiedTime = currentModifiedTime;
            return true;
        }
        return false;
    }

    public void canExecuteCommand() {
        if (this.isFileModified()) {
            this.executeCommand();
        }
    }

    public void executeCommand() {
        if (command == null) return;
        Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof FileListener)) return false;
        FileListener that = (FileListener) o;
        return Objects.equals(getFile(), that.getFile());
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(getFile());
    }

    @Override
    public String toString() {
        return "FileListener{" +
                "file=" + file.getAbsolutePath() +
                '}';
    }

}
